package com.example.lib_mvp.base;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MotionEvent;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.lib_mvp.AppInfoUtils;
import com.example.lib_mvp.BuildConfig;
import com.example.lib_mvp.apkupload.CheckApkUtil;
import com.example.lib_mvp.musicService.MusicService;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tjf.lib_core.BaseActivity;
import com.tjf.lib_network.SpSaveUtils;
import com.tjf.lib_utils.EventBusUtils;
import com.tjf.lib_utils.KeyboardUtils;
import com.tjf.lib_utils.LogsUtils;
import com.tjf.lib_utils.ShareUtils;
import com.tjf.lib_utils.SoundPlayManager;
import  com.example.lib_mvp.R;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Random;

import tech.gujin.toast.ToastUtil;


public abstract class AppBaseActivity extends BaseActivity {

    SoundPlayManager soundPlayManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化 SoundPlayManager，最多同时播放 5 个音频
        soundPlayManager = new SoundPlayManager(this, 5);
        LogsUtils.i("soundPlayManager 初始化");
    }

    @Override
    public void onTokenPastDue() {
        super.onTokenPastDue();
        SpSaveUtils.setToken("");
        LogsUtils.i("token失效了 进行登录");
        // TODO: 2025/2/17
//        startActivity(LoginCodeActivity.class);
//        finish();
    }

    public void showToastMsg(String msg) {
        ToastUtil.show(msg);
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean hide_dispatchTouchEvent = KeyboardUtils.hide_dispatchTouchEvent(this, ev);
        return hide_dispatchTouchEvent ? super.dispatchTouchEvent(ev)   // 必不可少，否则所有的组件都不会有TouchEvent了
                : getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }


    @Override
    protected void onResume() {
        super.onResume();
//        XXPermissions.with(this).permission(
//                Permission.MANAGE_EXTERNAL_STORAGE).request((permissions, all) -> {
//            Log.i("权限", "读写权限==" + all);
//        });
        CheckApkUtil checkApkUtil = new CheckApkUtil(this);
        checkApkUtil.getVersion(null, AppInfoUtils.getVersionName(getActivity() ));
    }

    @Override
    protected boolean registerEventBus() {
        return true;
    }


    /**
     * 替换fragment
     */
    public void setReplacementPage(int resId, AppBaseFragment appBaseFragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        String tag = appBaseFragment.getClass().getSimpleName();
        LogsUtils.i("-setReplacementPage-" + tag);
//        Fragment existingFragment = fragmentManager.findFragmentByTag(tag);
//        if (existingFragment != null) {
//            LogsUtils.i("已经添加-" + tag);
//            return;
//        }
        // 开启一个事务
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(resId, appBaseFragment);
//        fragmentTransaction.addToBackStack(null);
        // 提交事务
        fragmentTransaction.commit();
    }

    /**
     * 跳转到扫一扫页面 及回调数据的发送
     *
     * @param context
     */
    public void startScanPage(Activity context) {
//        Intent intent = new Intent(context, ScanActivity.class);
//        startActivityForResult(intent, (resultCode, data) -> {
//            if (resultCode == RESULT_OK && data != null) {
//                String result = CameraScan.parseScanResult(data);
//                LogsUtils.i("扫一扫=resultCode=" + resultCode, "result=" + result);
//                EventBusUtils.sendEvent(Constant.OtherConstant.SAO_YI_SAO_RESULT, 0, "扫一扫", result);
//            }
//        });
    }


    public void setSmartRefresh(SmartRefreshLayout smartRefreshLayout,
                                OnRefreshLoadMoreListener listener) {
        ClassicsFooter classicsFooter = new ClassicsFooter(this);
        ClassicsHeader classicsHeader = new ClassicsHeader(this);
        smartRefreshLayout.setRefreshHeader(classicsHeader);
        smartRefreshLayout.setRefreshFooter(classicsFooter);
        smartRefreshLayout.setOnRefreshLoadMoreListener(listener);
    }

    public void setSmartRefreshHeader(SmartRefreshLayout smartRefreshLayout,
                                      OnRefreshListener listener) {
        ClassicsHeader classicsHeader = new ClassicsHeader(this);
        smartRefreshLayout.setRefreshHeader(classicsHeader);
        smartRefreshLayout.setOnRefreshListener(listener);
    }

    public void setEmptyView(BaseQuickAdapter adapter, RecyclerView recyclerView) {
        adapter.setEmptyView(R.layout.layout_empty, recyclerView);

    }


    public MusicService.MusicBinder musicBinder;
    public MusicServiceConnection musicServiceConnection;
    boolean isBind = false;
    private static final int BIND_AUTO_CREATE = Service.BIND_AUTO_CREATE;

    public void startAndBindService() {
        LogsUtils.i("startAndBindService==启动音乐服务=");

        Intent intent = new Intent(getActivity(), MusicService.class);
        musicServiceConnection = new MusicServiceConnection();
//        getActivity().startService(intent);
        bindService(intent, musicServiceConnection, BIND_AUTO_CREATE);
    }

    public void stopAndBindService() {
        if (musicBinder != null) {
            musicBinder.stopPlay();
        }
        LogsUtils.i("stopAndBindService=开始解除音乐服务=");
        unbindService(musicServiceConnection);
//        Intent intent = new Intent(getActivity(), MusicService.class);
//        getActivity().stopService(intent);
    }

    class MusicServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicBinder = (MusicService.MusicBinder) service;
            isBind = true;
            LogsUtils.i("onServiceConnected=数据==绑定音乐服务成功=");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    public void setIndexTabFragment(int indexTabFragment) {
        ShareUtils.getInstance().putInt("indexTabFragment", indexTabFragment);
    }

//    @Override
//    public void onBackPressed() {
//        super.onBackPressed();
//        if (getActivity() instanceof MainActivity) {
////            finish();
//        } else {
//            if (getActivity() instanceof LoginCodeActivity ||
//                    getActivity() instanceof LoginActivity ||
//                    getActivity() instanceof ScanActivity ||
//                    getActivity() instanceof AuthOrderActivity) {
//
//            } else {
//                startActivity(MainActivity.class);
//                finish();
//            }
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
        soundPlayManager.release();
    }

//    public void startVosk() {
//        Intent serviceIntent = new Intent(this, VoskService.class);
//        startService(serviceIntent);  // 启动 Service
//    }
//
//    public void stopVosk() {
//        Intent serviceIntent = new Intent(this, VoskService.class);
//        stopService(serviceIntent);  // 启动 Service
//    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventReceived(VoskEvent event) {
//        String message = event.getMsg();
//        Log.d("TranslationService", "收到消息：" + message);
////        showToastMsg(message);
//        toPage(message, event);
//    }


//    public void toPage(String message, VoskEvent event) {
//        switch (event.getCode()) {
//            case -1:
//                int randomNumber = generateRandomNumber();
//                if (soundPlayManager != null) {
//                    soundPlayManager.playSound(
//                            randomNumber == 1 ? R.raw.close1 : randomNumber == 2 ? R.raw.close1 : R.raw.close3);
//                }
//                break;
//            case 0:
//                toPageContext(MainActivity.class);
//                break;
//            case 1:
//                randomNumber = generateRandomNumber();
//                if (soundPlayManager != null) {
//                    soundPlayManager.playSound(
//                            randomNumber == 1 ? R.raw.h1 : randomNumber == 2 ? R.raw.h2 : R.raw.h3);
//                }
//                break;
//            case 2:
//                toPageContext(RecordToHyjyActivity.class);
//
//                break;
//            case 3:
//                toPageContext(RecordToKtbjActivity.class);
//
//                break;
//            case 4:
//                toPageContext(RecordToTextActivity.class);
//
//                break;
//            case 5:
//                toPageContext(DiscoveringMusicActivity.class);
//
//                break;
//            case 6:
//                toPageContext(TransTcsyActivity.class);
//
//                break;
//
//            case 23:
//                if (soundPlayManager != null) {
//                    soundPlayManager.playSound(R.raw.close1);
//                }
//                break;
//            case 24:
//                if (soundPlayManager != null) {
//                    soundPlayManager.playSound(R.raw.intro1);
//                }
//                break;
//            case 25:
//                if (soundPlayManager != null) {
//                    soundPlayManager.playSound(R.raw.intro2);
//                }
//                break;
//            default:
//                otherVosk(message, event);
//                break;
//        }
//    }

    public static int generateRandomNumber() {
        Random random = new Random();
        // nextInt(bound) 会生成一个 [0, bound) 范围的随机整数
        // 所以我们生成 [0, 3) 的随机数，再加上1就得到 [1, 4) 即 [1, 3] 的随机数
        return random.nextInt(3) + 1;
    }

//    public void otherVosk(String message, VoskEvent event) {
//
//
//    }

    public void toPageContext(Class<? extends Activity> clazz) {
        if (isShowActivity(this, clazz)) {
            if (soundPlayManager != null) {
                soundPlayManager.playSound(R.raw.pe3);
            }
            showToastMsg("已经在当前页了");
            return;
        }
        startActivity(clazz);
        finish();
    }

    public boolean isShowActivity(Context context, Class<? extends Activity> clazz) {
        // 获取当前 Activity 的类名
        String currentActivityName = ((Activity) context).getLocalClassName();
        // 获取目标 Activity 的类名
        String targetActivityName = clazz.getName();

        // 比较当前 Activity 和目标 Activity 是否相同
        return currentActivityName.equals(targetActivityName);
    }
}
